package com.lingjtx.common.other.helper;

import com.alibaba.fastjson2.JSON;
import com.lingjtx.common.core.handle.ObjectPool;
import com.lingjtx.common.core.util.BeanUtil;
import com.lingjtx.common.core.util.CommonUtil;
import com.lingjtx.common.core.util.DateTimeUtil;
import com.lingjtx.common.other.http.Call;
import com.lingjtx.common.other.http.Callback;
import com.lingjtx.common.other.http.Network;
import com.lingjtx.common.other.http.RemoteService;
import com.lingjtx.common.other.model.sms.SmsCodeResponse;
import com.lingjtx.common.other.model.sms.SmsRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.http.HttpClient;
import java.util.Objects;
import java.util.UUID;

public class SmsHelper {
    public static final Logger log = LoggerFactory.getLogger(SmsHelper.class);

    /**
     * 发送短信
     */
    public static void sendSms(SmsRequest model, ObjectPool<HttpClient> objectPool) {
        try {
            model.setSignatureNonce(UUID.randomUUID().toString());
            model.setTimestamp(DateTimeUtil.formatGMTDate());
            String sign = CommonUtil.stringToSign(BeanUtil.covertMap(model));
            model.setSignature(sign);
            RemoteService service = Network.remote(RemoteService.class, objectPool);
            Call<SmsCodeResponse> call = service.sendSms(model);
            call.enqueue(new SmsRspCallback());
        } catch (Exception e) {
            log.error("阿里云接口验签异常：{}", e.getMessage());
        }
    }

    /**
     * 阿里云请求响应结果回调
     */
    private static class SmsRspCallback implements Callback<SmsCodeResponse> {

        @Override
        public void onResponse(SmsCodeResponse rspModel) {
            // 请求成功
            if (rspModel != null && Objects.equals(rspModel.getCode(), "OK")) {
                log.info("短信发送成功，RequestId : {}", rspModel.getRequestId());
            } else {
                log.error("短信发送失败，info : {}", JSON.toJSONString(rspModel));
            }
        }

        @Override
        public void onFailure(String str) {
            log.error("SmsHelper 请求失败，info : {}", str);
        }
    }
}
